<template>
  <div>
    <Total :homeData="homeData"></Total>

    <!-- <div class="card transform">
      <div>
        <h4>最近48小时在线人数（整点为准）</h4>
        <div id="historyMemberChart"></div>
      </div>
    </div> -->
    <!-- chart -->
    <!-- <div class="charts  flex">
      <div class="chart-item">
        <h4>流量走势</h4>
        <div id="pvChart"></div>
      </div>
      <div class="chart-item">
        <h4>交易趋势</h4>
        <div id="orderChart"></div>
      </div>
    </div> -->

    <!-- top10商品 -->
    <div class="card transform">
      <h4>热卖商品TOP10</h4>
      <Table
        stripe
        :columns="tophotGoodsColumns"
        :data="topHotGoodsData"
      ></Table>
    </div>

    <!-- top10店铺 -->
    <div class="card transform">
      <h4>热卖店铺TOP10</h4>
      <Table
        stripe
        :columns="tophotShopsColumns"
        :data="topHotShopsData"
      ></Table>
    </div>

    <!-- chart -->
    <div class="card" style="padding-top: 70px">
      <div class="reports">
        <div class="reports-one">
          <div class="reports-date">
            <div class="reports-title">人员统计</div>
            <RadioGroup
              v-model="quickTime"
              @on-change="handleChangeQuickTime($event, 'value1')"
              type="button"
              style="margin-right: 15px"
            >
              <Radio label="本周"></Radio>
              <Radio label="本月"></Radio>
              <Radio label="今年"></Radio>
            </RadioGroup>
            <DatePicker
              :value="value1"
              format="yyyy-MM-dd"
              type="daterange"
              placement="bottom-end"
              placeholder="请选择时间"
              style="width: 200px"
              @on-change="handleChangeTime($event, 'quickTime')"
            ></DatePicker>
          </div>
          <line-echartxy
            v-if="oneData.data"
            eId="lineOne"
            :dataSource="oneData"
          />
        </div>
        <div class="reports-two">
          <div class="reports-date">
            <div class="reports-title">金额统计</div>
            <RadioGroup
              v-model="quickTime2"
              @on-change="handleChangeQuickTime($event, 'value2')"
              type="button"
              style="margin-right: 15px"
            >
              <Radio label="本周"></Radio>
              <Radio label="本月"></Radio>
              <Radio label="今年"></Radio>
            </RadioGroup>
            <DatePicker
              :value="value2"
              format="yyyy-MM-dd"
              type="daterange"
              placement="bottom-end"
              placeholder="请选择时间"
              style="width: 200px"
              @on-change="handleChangeTime($event, 'quickTime2')"
            ></DatePicker>
          </div>
          <line-echartxy
            v-if="twoData.data"
            eId="lineTwo"
            :dataSource="twoData"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  homeStatistics,
  hotGoods,
  hotShops,
  getNoticePage,
  homeStatisticsOne,
  homeStatisticsTwo
} from "@/api/index";
import * as API_Goods from "@/api/goods";
import LineEchartxy from "./modules/LineEchartxy";
import { Chart } from "@antv/g2";
import * as API_Member from "@/api/member";
import {
  getMonthFirstLastDay,
  getYearFirstLastDay,
  getWeekFirstLastDay,
  formatTime,
} from "@/utils/formatTime.js";
// import i18nBox from '@/views/lili-components/i18n-translate'
import Total from "./modules/total.vue";
export default {
  components: {
    LineEchartxy,
    Total,
  },
  name: "home",
  // components:{
  //   i18nBox
  // },
  data() {
    return {
      oneData: {},
      quickTime: "本周",
      twoData: {},
      quickTime2: "本周",
      // 测试数据
      test: {
        a: "test",
        languages: [],
      },
      // 测试数据结束
      tophotShopsColumns: [
        // 表格表头
        {
          type: "index",
          width: 100,
          title: "排名",
          align: "center",
        },
        {
          title: "店铺名称",
          key: "storeName",
        },

        {
          title: "价格",
          key: "price",
          render: (h, params) => {
            return h(
              "div",
              this.$options.filters.unitPrice(params.row.price, "焕贝")
            );
          },
        },
        {
          title: "销量",
          key: "num",
          width: 100,
          sortable: true,
        },
      ],

      tophotGoodsColumns: [
        {
          type: "index",
          width: 100,
          title: "排名",
          align: "center",
        },
        {
          title: "商品名称",
          key: "goodsName",
        },

        {
          title: "价格",
          key: "price",
          render: (h, params) => {
            return h(
              "div",
              this.$options.filters.unitPrice(params.row.price, "焕贝")
            );
          },
        },
        {
          title: "销量",
          key: "num",
          width: 100,
          sortable: true,
        },
      ],
      topHotGoodsData: [], //热卖商品集合
      topHotShopsData: [], //热卖店铺集合
      awaitTodoData: "", //今日待办集合
      homeData: {}, // 首页数据
      pvChart: "", // 流量统计
      orderChart: "", // 订单统计
      historyMemberChart: "", // 最近会员流量统计
      params: {
        // 请求参数
        searchType: "LAST_SEVEN",
      },
      // 订单传参
      orderParams: {
        searchType: "LAST_SEVEN", // TODAY ,  YESTERDAY , LAST_SEVEN , LAST_THIRTY
        year: "",
        shopId: "",
        memberId: "",
      },
      value1: ["", ""],
      value2: ["", ""],
    };
  },
  methods: {
    handleChangeTime(val, type) {
      let timeType = type === "quickTime" ? "value1" : "value2";
      this[timeType] = val;
      if (!val || !val[0]) {
        this[type] = "本周";
        this.handleChangeQuickTime("本周", timeType);
        return;
      }
      this[type] = "";
      if (type === "quickTime") {
        this.getHomeStatisticsOne();
      } else {
        this.getHomeStatisticsTwo();
      }
    },
    handleChangeQuickTime(val, type) {
      if (!val) return;
      let time = {};
      let state = null;
      if (val === "本周") {
        time = getWeekFirstLastDay();
      }
      if (val === "本月") {
        time = getMonthFirstLastDay();
      }
      if (val === "今年") {
        time = getYearFirstLastDay();
        state = "year";
      }
      this[type] = [time.firstDay, time.lastDay];
      if (type === "value1") {
        this.getHomeStatisticsOne(state);
      } else {
        this.getHomeStatisticsTwo(state);
      }
    },
    getHomeStatisticsOne(state) {
      homeStatisticsOne({
        startTime: this.value1[0],
        endTime: this.value1[1],
        state: state,
      }).then((res) => {
        let xAxis = [];
        if (state) {
          res.result.date.forEach((item) => {
            xAxis.push(formatTime(item, "MM"));
          });
        } else {
          res.result.date.forEach((item) => {
            xAxis.push(formatTime(item, "MM-dd"));
          });
        }
        if (!this.oneData.data) {
          this.oneData = {
            data: [
              res.result.partnerTs,
              res.result.partnerSy,
              res.result.members,
            ],
            legend: ["天使合伙人", "事业合伙人", "C端会员"],
            xAxis: xAxis,
            colors: [
              "#dd3ee5",
              "#12e78c",
              "#fe8104",
              "#01C2F9",
              "#4B7CF3",
              "#FD9E06",
            ],
            unit: "人",
          };
        } else {
          this.$set(this.oneData, "data", [
            res.result.partnerTs,
            res.result.partnerSy,
            res.result.members,
          ]);
          this.$set(this.oneData, "xAxis", xAxis);
        }
      });
    },
    getHomeStatisticsTwo(state) {
      homeStatisticsTwo({
        startTime: this.value2[0],
        endTime: this.value2[1],
        state: state,
      }).then((res) => {
        let xAxis = [];
        if (state) {
          res.result.date.forEach((item) => {
            xAxis.push(formatTime(item, "MM"));
          });
        } else {
          res.result.date.forEach((item) => {
            xAxis.push(formatTime(item, "MM-dd"));
          });
        }
        if (!this.twoData.data) {
          this.twoData = {
            data: [
              res.result.memberMoney,
              res.result.rechargeMoney,
              res.result.consumptionC,
              res.result.partnerConsumption,
            ],
            legend: [
              "会员费总额",
              "充值总额",
              "c端消费总额",
              "合伙人身份消费总额",
            ],
            xAxis: xAxis,
            colors: [
              "#FD9E06",
              "#4B7CF3",
              "#01C2F9",
              "#fe8104",
              "#12e78c",
              "#dd3ee5",
            ],
            unit: '元'
          };
        } else {
          this.$set(this.twoData, "data", [
            res.result.memberMoney,
            res.result.rechargeMoney,
            res.result.consumptionC,
            res.result.partnerConsumption,
          ]);
          this.$set(this.twoData, "xAxis", xAxis);
        }
      });
    },
    // 路由跳转
    navigateTo(name) {
      this.$router.push({
        name,
      });
    },
    // top10热卖商品
    async toHotGoods() {
      let res = await hotGoods(this.params);
      res.success ? (this.topHotGoodsData = res.result) : "";
    },

    // top10热卖店铺
    async topHotShops() {
      let res = await hotShops(this.params);
      res.success ? (this.topHotShopsData = res.result) : "";
    },
    // 今日待办
    async awaitTodo() {
      let res = await getNoticePage();
      res.success ? (this.awaitTodoData = res.result) : "";
    },

    //首页统计数据
    async getHomeData() {
      let res = await homeStatistics();
      if (res.success) {
        if (
          res.result.todayOrderPrice &&
          res.result.todayOrderPrice != "null"
        ) {
          res.result.todayOrderPrice = parseInt(res.result.todayOrderPrice);
        } else {
          res.result.todayOrderPrice = 0;
        }

        this.homeData = res.result;
      }
    },

    // 实例化订单图表
    async initOrderChartList(name) {
      const res = await API_Goods.getOrderChart(this.orderParams);
      if (res.success) {
        this.chartList = res.result;

        if (!this.orderChart) {
          this.orderChart = new Chart({
            container: "orderChart",
            autoFit: true,
            height: 500,
            padding: [70, 70, 70, 70],
          });
        }

        this.initOrderChart(); //订单表
      }
    },

    // 订单表
    initOrderChart() {
      // 默认已经加载 legend-filter 交互
      let data = this.chartList;

      data.forEach((item) => {
        item.createTime = item.createTime.split(" ")[0];
        item.title = "交易额";
      });
      this.orderChart.data(data);

      this.orderChart.tooltip({
        showCrosshairs: true,
        shared: true,
      });

      this.orderChart
        .line()
        .position("createTime*price")
        .label("price")
        .color("title")
        .shape("smooth");

      this.orderChart
        .point()
        .position("createTime*price")
        .label("price")
        .color("title")
        .shape("circle")
        .style({
          stroke: "#fff",
          lineWidth: 1,
        });
      this.orderChart.render();
    },

    // 浏览量统计图
    initPvChart() {
      let uv = [];
      let pv = [];
      this.data.forEach((item) => {
        uv.push({
          date: item.date,
          uvNum: item.uvNum,
          title: "访客数UV",
          pv: item.uvNum,
        });

        pv.push({
          date: item.date,
          pvNum: item.pvNum,
          pv: item.pvNum,
          title: "浏览量PV",
        });
      });

      let data = [...uv, ...pv];

      this.pvChart.data(data);
      this.pvChart.scale({
        activeQuantity: {
          range: [0, 1],
          nice: true,
        },
      });
      this.pvChart.tooltip({
        showCrosshairs: true,
        shared: true,
      });

      this.pvChart
        .line()
        .position("date*pv")
        .color("title")
        .label("pv")
        .shape("smooth");

      this.pvChart
        .point()
        .position("date*pv")
        .color("title")
        .label("pv")
        .shape("circle")
        .style({
          stroke: "#fff",
          lineWidth: 1,
        });

      this.pvChart.render();
    },

    // 浏览量
    async getPvChart() {
      API_Member.getStatisticsList(this.params).then((res) => {
        if (res.result) {
          this.data = res.result;

          if (!this.pvChart) {
            this.pvChart = new Chart({
              container: "pvChart",
              autoFit: true,
              height: 500,
              padding: [70, 70, 70, 70],
            });
          }
          this.initPvChart();
        }
      });
    },
    // 实例化会员流量图表
    async initHistoryMemberChartList() {
      const res = await API_Member.historyMemberChartList();
      if (res.success) {
        this.chartList = res.result;

        if (!this.historyMemberChart) {
          this.historyMemberChart = new Chart({
            container: "historyMemberChart",
            autoFit: true,
            height: 500,
            padding: [70, 70, 70, 70],
          });
        }

        this.initHistoryMemberChart();
      }
    },
    // 历史在线人数
    initHistoryMemberChart() {
      // 默认已经加载 legend-filter 交互
      let data = this.chartList;

      data.forEach((item) => {
        item.title = "历史在线人数";
        item.date = item.date.substring(5);
      });
      this.historyMemberChart.data(data);

      this.historyMemberChart.tooltip({
        showCrosshairs: true,
        shared: true,
      });

      this.historyMemberChart
        .line()
        .position("date*num")
        .color("title", ["#ffaa71"])
        .shape("smooth");

      this.historyMemberChart
        .point()
        .position("date*num")
        .color("title", ["#ffaa71"])
        .shape("circle");
      this.historyMemberChart.render();
    },
    // 初始化信息
    init() {
      this.toHotGoods();
      this.topHotShops();
      this.awaitTodo();
      this.getHomeData();
      // this.getPvChart();
      // this.initOrderChartList();
      // this.initHistoryMemberChartList();
    },
  },
  mounted() {
    this.init();
    let time = getWeekFirstLastDay();
    this.value1 = [time.firstDay, time.lastDay];
    this.value2 = [time.firstDay, time.lastDay];
    this.getHomeStatisticsOne();
    this.getHomeStatisticsTwo();
  },
};
</script>
<style lang="scss" scoped>
@import "./home.scss";
</style>
